<template>
    <div class="common-layout"
        style="display: flex; width: 100%;justify-content: space-between;background-color: white;place-items: center;">
        <el-image style=" height: 60px;width: auto;margin-left: 1.5%;cursor: pointer;" :src="longLogo"
            @click="GoMainpage" />

        <el-text class="mx-1" type="primary"
            style=" font-size:x-large; color: #DC0000;width: fit-content;margin-right: 6%;">玄之又玄，让思想升腾</el-text>

        <el-input v-model="searchInput" style="width: 240px;height: 40px;margin-right: 5%;" @keyup.enter="handleSearch"
            placeholder="Please input to search" />

        <el-button @click="GoBlogCreate" style="margin-right: 10%">
            创建博客</el-button>

        <el-avatar :size="50" :src="userImageUrl" @click="PushUserPage" style="cursor: pointer;margin-right: 0%;" />

        <div style="margin-right: 3%;">
            <el-button v-if="userPicture != null" @click="loginOut">
                退出登录</el-button>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router'; // 引入路由
import logo from '@/assets/logo.png'
import longLogo from '@/assets/longLogo.png'
import userImage from '@/assets/userImage.png'
import { IsLoginIn, Revoke } from '../functions/IsLoginIn.vue';
import axios from 'axios'

const searchInput = ref(''); // 使用 ref 来创建响应式的数据
const router = useRouter(); // 创建路由实例

const userImageUrl = ref('');

const userPicture = localStorage.getItem('userPicture');

if (userPicture == null) {
    userImageUrl.value = userImage;
}
else {
    userImageUrl.value = userPicture;
}

console.log(userPicture);

const props = defineProps({
    ChangeUrl: Function
});

function GoMainpage() {
    router.push('/');
    props.ChangeUrl('/api/blog/getcache');
}

// 定义搜索函数
function handleSearch() {
    if (searchInput.value.trim() !== '') {
        // 根据 searchInput 的值进行搜索跳转
        // 假设有一个路由地址 '/search' 用于搜索结果页面
        router.push({ path: '/search', query: { keyword: searchInput.value } });
    }
}

function PushUserPage() {
    // console.log(props.data);
    if (userPicture == null) {
        router.push('/login');
    }
    else {
        router.push({ path: '/user', query: { id: localStorage.getItem('userId') } });
    }
}

function GoBlogCreate() {
    IsLoginIn();
    router.push('/blogCreate');
}

function loginOut() {
    IsLoginIn();
    axios
        .post('/api/user/loginOut', {
        }, {
            headers: {
                'HOSHINO_T_KK': localStorage.getItem('userToken'),
            }
        })
        .then(response => {
            console.log(response);
            localStorage.clear();
            // userPicture=null;
            // userImageUrl.value=userImage;
            window.location.reload(true);
        })
        .catch(function (error) { // 请求失败处理
            console.log(error);
        });
}
</script>